package com.ms.user.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ms.commons.domain.SysPermission;
import com.ms.commons.domain.SysRole;
import com.ms.commons.domain.SysUser;
import com.ms.user.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import utils.Result;

import java.util.List;
import java.util.UUID;

/**
 * @author:SmartV
 * @date:2021/12/2 12:49
 */
@RestController
@RequestMapping("/user")
public class SysUserController {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    private ISysUserService userService;
    @GetMapping("/login")
    public Result login(@RequestParam("username") String username , @RequestParam("password") String password){
        SysUser user = userService.getOne(new QueryWrapper<SysUser>().eq("username", username).eq("password", password));
        if (user==null){
            return Result.error("账户或密码错误",null);
        }
        //存redis
        List<SysPermission> permissions = userService.getPermissionByUserId(user.getId());
        List<SysRole> roles = userService.findRoleByUserId(user.getId());
        user.setPermissions(permissions);
        user.setRoles(roles);
        String userString = JSON.toJSONString(user);
        String uuid = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(uuid,userString);
        return Result.ok(uuid);
    }
}
